package service

import (
	"fmt"

	"github.com/google/uuid"
	"github.com/smash-llj/Nexa-server/models"
	"github.com/smash-llj/Nexa-server/models/request"
	"github.com/smash-llj/Nexa-server/utils"
)

var userService *UserService

type UserService struct {
	BaseService
}

func NewUserService() *UserService {
	if userService == nil {
		return &UserService{
			NewBaseService(),
		}
	}
	return userService
}

func (ud *UserService) Login(loginReq request.UserLoginReq) (models.User, error) {
	var user models.User
	// 根据用户名查找用户
	err := ud.Gorm.Model(models.User{}).Where("username = ?", loginReq.Name).First(&user).Error
	if err != nil {
		return models.User{}, fmt.Errorf("用户名不存在")
	}
	//验证密码
	if !utils.CheckCrypt(user.Password, loginReq.Password) {
		return models.User{}, fmt.Errorf("密码错误")
	}
	return user, nil
}

func (ud *UserService) Register(registerReq request.UserRegisterReq) error {
	// 1. 使用更高效的查询方式检查用户是否存在
	var exists bool
	if err := ud.Gorm.Model(&models.User{}).
		Select("1").
		Where("username = ?", registerReq.Name).
		Limit(1).
		Find(&exists).Error; err != nil {
		return fmt.Errorf("检查用户存在性失败: %v", err)
	}
	if exists {
		return fmt.Errorf("用户名 %s 已被注册", registerReq.Name)
	}
	// 2. 密码加密错误处理
	enPassword, err := utils.EnCrypt(registerReq.Password)
	if err != nil {
		return fmt.Errorf("密码加密失败: %v", err)
	}
	// 3. 创建新用户
	newUser := models.User{
		UUID:     uuid.New().String(),
		Username: registerReq.Name,
		Password: enPassword,
	}
	if err := ud.Gorm.Create(&newUser).Error; err != nil {
		return fmt.Errorf("用户注册失败: %v", err)
	}
	return nil
}

func (ud *UserService) UpdateUserInfo(UId uint, UpdateReq request.UpdateUserInfoReq) error {
	result := ud.Gorm.Model(&models.User{}).Where("id = ?", UId).Updates(UpdateReq)
	if result.Error != nil {
		return result.Error
	}
	return nil
}
